package chapter_24.tcp.upload;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by Administrator
 * Created time 2018/8/10 13:18.
 * 案例:文件上传工具(服务端)
 */
public class UploadServer {

    public static void main(String[] args) {

        System.out.println("服务端程序运行...");

        try (// 创建一个 ServerSocket 监听端口的客户端请求
             ServerSocket serverSocket = new ServerSocket(6666);
             // 使用 accept() 阻塞当前线程,等待客户端请求
             Socket socket = serverSocket.accept();
             // 由 Socket 获得输入流,并创建缓冲输入流
             BufferedInputStream inputStream = new BufferedInputStream(socket.getInputStream());
             // 由文件输出流创建缓冲输出流
             FileOutputStream outputStream = new FileOutputStream("./src/chapter_24/tcp/upload/server.png")
        ) {
            // 缓冲区
            byte[] bytes = new byte[1024];
            // 首次从 Socket 读取数据
            int len = inputStream.read(bytes);

            while (len != -1) {
                // 写入数据文件
                outputStream.write(bytes, 0, len);
                // 再次从 Socket 读取数据
                len = inputStream.read(bytes);
            }

            System.out.println("接收文件完成!");

        } catch (IOException e) {
            System.out.println("IOException");
        }
    }
}
